package com.nowcoder.community.controller;

import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.*;
import com.nowcoder.community.utils.ConstantUtil;
import com.nowcoder.community.utils.GiteeImgBedUtil;
import com.nowcoder.community.utils.HostHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: shuhuang
 * @description:
 * @Date: 2022/10/1 22:55
 * @Version java version 1.8
 */
@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;

    @Value("${community.path.domain}")
    private String domain;
    /*@Value("${community.path.uploadPath}")
    private String uploadPath;*/
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Value("${spring.gitee.path}")
    private String path;

    @Autowired
    private LikeService likeService;
    @Autowired
    private FollowService followService;
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private CommentService commentService;

    //@LoginRequired
    @GetMapping(path = "/setting")
    public String getSettingPage() {
        return "/site/setting";
    }

    /*@LoginRequired*/
    @PostMapping(path = "/upload")
    @ResponseBody
    public Map<String, Object> uploadPath(@RequestParam("file") MultipartFile headerImage, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        if (headerImage == null) {
            logger.error("方法参数MultipartFile接受的文件不能为空！");
            throw new IllegalArgumentException("方法参数异常");
        }
        String filename = headerImage.getOriginalFilename();
        //.png,.jpg,.icon......
        String suffix = filename.substring(filename.lastIndexOf("."));
        String[] strings = {".png", ".jpg", ".jpeg", ".icon"};
        for (int i = 0; i < strings.length; i++) {
            if (suffix.equalsIgnoreCase(strings[i])) {
                break;
            } else {
                if (i == strings.length - 1 && !suffix.equalsIgnoreCase(strings[strings.length - 1])) {
                    map.put("msg", "图片格式不正确，请重新选择！");
                    return map;
                }
            }
        }
        map = GiteeImgBedUtil.upload(path, headerImage);
        //更新当前用户头像的路径（web访问的路径）
        User user = hostHolder.getUser();
        if (Integer.parseInt(map.get("code").toString()) == 200) {
            //更新当前用户头像的路径（web访问的路径）
            userService.updateHeaderImage(user.getId(), map.get("accessUrl").toString());
        }
        return map;
    }

   /* @GetMapping(path = "/header/{fileName}")
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        //服务器存放路径
        fileName = uploadPath + "/" + fileName;
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //响应图片
        response.setContentType("image/" + suffix);
        try (
                //找到文件的位置作为文件操作流
                FileInputStream fis = new FileInputStream(fileName);
                OutputStream os = response.getOutputStream();
        ) {
            byte[] bytes = new byte[1024];
            int b = 0;
            while ((b = fis.read(bytes)) != -1) {
                os.write(bytes, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败！" + e.getMessage());
        }
    }*/

    /**
     * 用户修改密码
     */
    @PostMapping(path = "/changePw")
    public String changePassword(Model model, String oldPassword, String newPassword,
                                 @CookieValue("ticket") String ticket) {
        User user = hostHolder.getUser();
        if (user != null) {
            Map<String, Object> map = userService.alterPassword(user.getId(), oldPassword, newPassword);
            if (map != null && !map.isEmpty()) {
                model.addAllAttributes(map);
                return "/site/setting";
            }
            //修改登录凭证为失效状态
            userService.logout(ticket);
        }
        return "redirect:/login";
    }

    /**
     * 个人主页[每个人的主页点击头像都能访问到]
     */
    @GetMapping(path = "/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在！");
        }
        //用户
        model.addAttribute("user", user);
        //点赞数量
        int userLikeCount = likeService.findUserLikeCount(userId);
        //关注数量
        long followeeCount = followService.findFolloweeCount(userId, ConstantUtil.ENTITY_TYPE_USER);
        //粉丝数量
        long followerCount = followService.findFollowerCount(ConstantUtil.ENTITY_TYPE_USER, userId);
        model.addAttribute("userLikeCount", userLikeCount);
        model.addAttribute("followeeCount", followeeCount);
        model.addAttribute("followerCount", followerCount);
        //是否已关注
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ConstantUtil.ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);

        return "/site/profile";
    }

    /**
     * 查看我的帖子
     */
    @GetMapping(path = "/myPost/{userId}")
    public String getMyPostPage(@PathVariable(value = "userId") int userId, Model model, Page page) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在！");
        }
        int postRows = discussPostService.findDiscussPostRows(userId);
        //评论信息的分页查询
        page.setPath("/user/myPost/" + userId);
        page.setRows(postRows);

        List<DiscussPost> discussPosts = discussPostService.findDiscussPosts(userId, page.getOffset(), page.getLimit(), 0);
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (discussPosts != null) {
            for (DiscussPost dpost : discussPosts) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", dpost);
                long likeCount = likeService.findEntityLikeCount(ConstantUtil.ENTITY_TYPE_POST, dpost.getId());
                map.put("likeCount", likeCount);
                mapList.add(map);
            }
        }
        model.addAttribute("userId", userId);
        model.addAttribute("postRows", postRows);
        model.addAttribute("discussPosts", mapList);
        return "/site/my-post";
    }

    /**
     * 查看我的回复
     */
    @GetMapping(path = "/myReply/{userId}")
    public String getMyReplyPage(@PathVariable("userId") int userId, Model model, Page page) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在！");
        }
        int commentRows = commentService.findCountByUserId(userId);
        page.setRows(commentRows);
        page.setPath("/user/myReply/" + userId);

        List<Comment> comments = commentService.findCommentByUserId(userId, page.getOffset(), page.getLimit());
        List<Map<String, Object>> mapList = new ArrayList<>();
        if (comments != null) {
            for (Comment coms : comments) {
                Map<String, Object> map = new HashMap<>();
                map.put("comment", coms);
                //获取回复的实体
                Comment comment = commentService.findCommentById(coms.getEntityId());
                map.put("content", comment.getContent());
                DiscussPost post = discussPostService.findDiscussPostById(comment.getEntityId());
                if (post != null) {
                    map.put("postId", post.getId());
                } else {
                    map.put("postId", 0);
                }
                mapList.add(map);
            }
        }
        model.addAttribute("userId", userId);
        model.addAttribute("commentRows", commentRows);
        model.addAttribute("myComments", mapList);

        return "/site/my-reply";
    }


}
